package cn.shengongying.utils;

import cn.shengongying.bean.BaseUser;
import cn.shengongying.exception.DigestException;
import cn.shengongying.exception.TokenExpireException;
import cn.shengongying.exception.TokenWrongException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultJwtBuilder;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * author: RXK
 * date: 2022/1/6 星期四
 * desc:
 */
public class JwtUtils {

    private JwtUtils() {
    }


    private static final String ISSUER = "cn/shengongying";

    private static final String key = "N2Fk/UI/+okSf2Uwb2xsgQ==";

    private static final String ENCRYPT_KEY = "P/EnHTDwAckpcxGDJfjIsQ==";

    public static final String USER = "user";

    public static String token(BaseUser baseUser) throws DigestException {
        Map<String, Object> user = new HashMap<>(2);
        user.put(USER, baseUser);
        String token = new DefaultJwtBuilder()
                .setId(baseUser.getId()
                        .toString())
                .setIssuer(ISSUER)
                .setIssuedAt(new Date())
                .setClaims(user)
                .signWith(SignatureAlgorithm.HS256, key.getBytes(StandardCharsets.UTF_8))
                .compact();
        token = Base64.getEncoder()
                .encodeToString(token.getBytes(StandardCharsets.UTF_8));
        return token;
    }


    public static BaseUser verifyToken(String token) throws TokenExpireException, TokenWrongException {
        byte[] decode = Base64.getDecoder()
                .decode(token);
        String s = new String(decode, StandardCharsets.UTF_8);

        try {
            Claims body = Jwts.parser()
                    .setSigningKey(key.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJwt(s)
                    .getBody();
             return  (BaseUser) body.get(USER);
        } catch (ExpiredJwtException e) {
            throw new TokenExpireException();
        } catch (MalformedJwtException | SignatureException | IllegalArgumentException e) {
            throw new TokenWrongException();
        }
    }
}
